package com.wkn.wknAdmin.controller;

import com.wkn.wknAdmin.entity.User;
import com.wkn.wknAdmin.result.ResultVO;
import com.wkn.wknAdmin.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title:
 * @Description:
 * @Author: WKN
 * CreateDate: 2022/8/12 0:44
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    ResultVO result = new ResultVO();


    /**
     * 获取全部用户
     *
     * @return
     */
    @GetMapping("/getAll")
    public ResultVO findAll() {
        List<User> userList = userService.findAll();
        return result.Success(userList);
    }

    /**
     * 添加或更新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/save")
    public ResultVO save(@RequestBody User user) {
        return userService.save(user);
    }


    @DeleteMapping("/deleteById/{id}")
    public ResultVO deleteById(@PathVariable Integer id) {
        int i = userService.deleteById(id);
        if (i > 0) {
            return result.Success("删除成功");
        }
        return result.Fail("删除失败");
    }


    @PostMapping("/batchDelete")
    public ResultVO batchDelete(@RequestBody List<Integer> ids) {
        int i = userService.batchDelete(ids);
        return result.Success("删除成功");
    }




    /**
     * 通过前端传数据进行分页查询
     * 获取记录总数
     *
     * @param pageNum  当前的页码数
     * @param pageSize 每页显示的数据条数
     * @return
     */
    @GetMapping("/page")
    public ResultVO findPage(@RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize,
                             @RequestParam("username") String username) {
        pageNum = (pageNum - 1) * pageSize;
        List<User> data = userService.selectPage(pageNum, pageSize, username);
        int totalCount = userService.getTotalCount(username);
        Map<String, Object> map = new HashMap<>();
        map.put("data", data);
        map.put("totalCount", totalCount);
        return result.Success(map);
    }


}
